<template>
	<div class="app-group-picker">
		<div class="app-group-picker__content">
			<div v-if="showTree" class="app-group-picker__content__select-tree">
				<a-tree
					:treeData="treeItems"
					:treeOnly="true"
					:treeCheckable="true"
					@select="treeSelect"
				>
				</a-tree>
			</div>
			<div class="app-group-picker__content__card">
				<div v-for="(group, index) in groupArr" :key="index">
					<div class="content__card__group-name">{{ group }}</div>
					<template v-for="(item, _index) in cardItems">
						<div
							:class="{
								content__card__item: true,
								'is-select': isSelect(item.id),
							}"
							v-if="group === item.group"
							:key="_index"
							@click="groupSelect({ id: item.id, label: item.label })"
						>
							{{ item.label }}
						</div>
					</template>
				</div>
			</div>
		</div>
		<div class="app-group-picker__footer">
			<AppButton
				@click="doEditorEmit"
				type="primary"
				:disabled="selects.length == 0"
				>{{ $t('common.groupselect.confirmbuttontext') }}</AppButton
			>
			<AppButton @click="doEditorEmit">{{
				$t('common.groupselect.cancelbuttontext')
			}}</AppButton>
		</div>
	</div>
</template>
<script lang="ts" setup>
import { IContext, IParam } from '@/core';
import { Ref } from 'vue';
import { Http } from '@/http';
interface Props {
	groupSelectContext?: IContext;
	groupSelectParam?: IParam;
}
const props = withDefaults(defineProps<Props>(), {});
const emit = defineEmits(['Change']);
let groupSelectContext: IContext = {}; //视图上下文
let groupSelectParam: IParam = {}; //参数
let multiple = false; //多选
let treeurl = ''; //树加载地址
let url = ''; //加载人员url
let requestMode: 'get' | 'post' | 'delete' | 'put' = 'get';
const selects: Ref<any[]> = ref([]); //数据选中集合
const treeItems: Ref<any[]> = ref([]); //树数据集
const cardItems: Ref<any[]> = ref([]); //分组表数据集
let groupArr: Ref<string[]> = ref([]);
//是否显示树
const showTree = computed(() => {
	if (props.groupSelectParam) {
		return props.groupSelectParam.showtree;
	}
});

//计算选中状态
const isSelect = computed(() => {
	return function (key: string) {
		if (
			selects.value.findIndex((select: any) => Object.is(select.id, key)) < 0
		) {
			return false;
		} else {
			return true;
		}
	};
});

onBeforeMount(() => {
	if (!props.groupSelectContext || !props.groupSelectParam) {
		return;
	}
	groupSelectContext = props.groupSelectContext;
	groupSelectParam = props.groupSelectParam;
	multiple = props.groupSelectParam.multiple;
	treeurl = props.groupSelectParam.treeurl;
	url = props.groupSelectParam.url;
	requestMode = props.groupSelectParam.requestMode;
	selects.value = [];
	if (props.groupSelectParam.selects) {
		props.groupSelectParam.selects.forEach((select: any) => {
			selects.value.push(select);
		});
	}
	load();
});

//加载数据
const load = () => {
	if (groupSelectParam.showtree) {
		loadTree();
	} else {
		loadGroupData(groupSelectParam.filtervalue);
	}
};

//加载树数据
const loadTree = () => {
	if (!treeurl) {
		return;
	}
	let orgid = groupSelectParam.filtervalue;
	let tempTreeUrl = '';
	if (
		groupSelectParam.selectType &&
		Object.is(groupSelectParam.selectType, 'dept')
	) {
		//加载部门人员数据
		tempTreeUrl = treeurl.replace('{deptId}', orgid);
	} else {
		tempTreeUrl = treeurl.replace('${orgid}', orgid);
	}
	Http.getHttp()({
		method: requestMode,
		url: tempTreeUrl,
		data: {},
	})
		.then((response: any) => {
			if (response && response.success) {
				const data = response.data;
				formatData(data);
				treeItems.value = data;
				if (treeItems.value.length > 0) {
					loadGroupData(treeItems.value[0].id);
				}
			}
		})
		.catch((error: any) => {
			App.getNotificationHelper().error(
				App.ts('common.generic.error', '错误'),
				error && error.message
					? error.message
					: App.ts('common.generic.requestexception', '请求异常')
			);
		});
};
//加载分组数据
const loadGroupData = (key: string) => {
	if (!url) {
		return;
	}
	let tempUrl = '';
	if (
		groupSelectParam.selectType &&
		Object.is(groupSelectParam.selectType, 'dept')
	) {
		tempUrl = url.replace('{deptId}', key);
	} else {
		if (url && url.indexOf('{deptId}') !== -1) {
			tempUrl = url.replace('{deptId}', key);
		} else {
			tempUrl = url.replace('${selected-orgid}', key);
		}
	}
	Http.getHttp()({
		method: requestMode,
		url: tempUrl,
		data: {},
	})
		.then((response: any) => {
			if (response && response.success) {
				computedGroup(response.data);
				cardItems.value = response.data;
			}
		})
		.catch((error: any) => {
			App.getNotificationHelper().error(
				App.ts('common.generic.error', '错误'),
				error && error.message
					? error.message
					: App.ts('common.generic.requestexception', '请求异常')
			);
		});
};

//树选中
const treeSelect = (event: any) => {
	loadGroupData(event[0]);
};

//分组表选中
const groupSelect = (data: any) => {
	if (!multiple) {
		selects.value = [data];
	} else {
		const index = selects.value.findIndex((item: any) =>
			Object.is(item.id, data.id)
		);
		if (index < 0) {
			selects.value.push(data);
		} else {
			selects.value.splice(index, 1);
		}
	}
};

//抛值
const doEditorEmit = () => {
	emit('Change', JSON.parse(JSON.stringify(selects.value)));
};

//格式化数据
const formatData = (data: any[]) => {
	data.forEach((item: any) => {
		if (!item.key) {
			item.key = item.id;
		}
		if (!item.title) {
			item.title = item.label;
		}
		if (item.children?.length > 0) {
			formatData(item.children);
		}
	});
};

//计算分组
const computedGroup = (data: any[]) => {
	groupArr.value = [];
	if (data instanceof Array && data.length > 0) {
		data.forEach((item: any) => {
			if (groupArr.value.indexOf(item.group) < 0) {
				groupArr.value.push(item.group);
			}
		});
	}
};
</script>
